<template>
    <!-- 单个考生分析 -->
    <div class="one-examinee-analysis" v-loading="loading">
        <el-row type="flex" justify="space-between">
            <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
                <el-form-item>
                    <!-- 选择考生-->
                    <el-select filterable @change="search(1)" v-model="searchForm.accounts" placeholder="请选择考生">
                        <el-option
                            v-for="item in examineeOptions"
                            :key="item.accountName"
                            :label="item.name"
                            :value="item.accountName">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item >
                    <!-- 日期范围 -->
                    <el-date-picker
                        v-model="searchForm.time"
                        type="daterange"
                        align="right"
                        unlink-panels
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd"
                        :picker-options="utils.intTimePickerOptions()"
                        @change="search">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
                </el-form-item>
            </el-form>
        </el-row>
        <!-- 场次统计 -->
        <p class="model-title">场次统计</p>
        <el-row class="exam-num-count-wrap">
            <el-col :span="12">
                <el-row class="overview-wrap exam-num-count-list" type="flex" justify="space-between">
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-4">{{ examNumInfo.totalNum }}场</p>
                            <p class="item-title">应参考场次</p>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-3">{{ examNumInfo.activeNum }}场</p>
                            <p class="item-title">实际参考场次</p>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="item-wrap">
                            <p class="item-value color-2">{{ examNumInfo.noActiveNum }}场</p>
                            <p class="item-title">缺考场次</p>
                        </div>
                    </el-col>
                </el-row>
            </el-col>
            <el-col :span="12">
                <div id="examNumCountEchart" class="echart-wrap"></div>
            </el-col>
        </el-row>
        <!-- 得分统计 -->
        <p class="model-title">得分统计</p>
        <el-row class="overview-wrap" type="flex" justify="space-between">
            <el-col :span="6">
                <div class="item-wrap">
                    <p class="item-value color-4">{{ examInfo.avgScore }}分</p>
                    <p class="item-title">平均得分</p>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="item-wrap">
                    <p class="item-value color-2">{{ examInfo.minScore }}分</p>
                    <p class="item-title">最低得分</p>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="item-wrap">
                    <p class="item-value color-3">{{ examInfo.maxScore }}分</p>
                    <p class="item-title">最高得分</p>
                </div>
            </el-col>
        </el-row>
        <el-row>    
            <el-col :span="24">
                <div class="examinee-score-distributed-wrap">
                    <p class="echart-title text-center">考试得分分布</p>
                    <P class="text-center">
                        <el-radio-group v-model="scoreType" @change="getExamScoreDistributedData">
                            <el-radio-button label=1>10分一个区间</el-radio-button>
                            <el-radio-button label=2>5分一个区间</el-radio-button>
                        </el-radio-group>
                    </P>
                    <div id="examScoreDistributedEchart" class="echart-wrap"></div>
                </div>
            </el-col>
        </el-row>
        <el-row>    
            <el-col :span="24">
                <div class="examinee-score-distributed-wrap" style="height: 415px;">
                    <p class="echart-title text-center">考试得分走势图</p>
                    <div id="examScoreTrendEchart" class="echart-wrap"></div>
                </div>
            </el-col>
        </el-row>
        <!-- 考试明细 -->
        <el-row>
            <el-col :span="20">
                <p class="model-title">考试明细</p>
            </el-col>
            <el-col :span="4">
                <el-row type="flex" justify="end">
                    <el-button type="primary" @click="exportDetail">导出明细</el-button>
                </el-row>
            </el-col>
        </el-row>
        <el-row type="flex" class="type-item-wrap">
            <el-col :span="24" class="exam-detail-table">
                <el-table
                    v-loading="loading"
                    border
                    ref="examDetailTable"
                    :data="tableData"
                    style="width: 100%">
                    <el-table-column label="序号" type="index" width="50"></el-table-column>
                    <el-table-column label="考试名称" prop="examName"></el-table-column>
                    <el-table-column label="总分" prop="totalScore"></el-table-column>
                    <el-table-column label="得分" prop="score">
                        <template slot-scope="scope">
                            <p>{{ scope.row.beginTime ? scope.row.score : '缺考'}}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="排名" prop="ranking"></el-table-column>
                    <el-table-column label="相对排名（按得分超过人数占总数的百分比计算）" prop="relateRanking">
                        <template slot-scope="scope">
                            <p>{{ scope.row.relateRanking ? scope.row.relateRanking+'%' : ''}}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="答题开始时间" prop="beginTime"></el-table-column>
                    <el-table-column label="耗时" prop="costTime"></el-table-column>
                    <el-table-column label="答卷明细" width="100">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.status == 2" @click="handleDetail(scope.row)" type="text" size="small">查看</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    background
                    small
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    :current-page.sync="currentPage"
                    :page-sizes="[10, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </el-col>
        </el-row>
        <!-- 考生答卷明细 -->
        <el-dialog
            :close-on-click-modal="false"
            title="答卷"
            width="1200px"
            top='10vh'
            v-if="dialogExamPaper"
            :visible.sync="dialogExamPaper"
            @close="closeExamPaper"
            v-dialogDrag>
            <examinee-answer-sheet-view :oldInfo="currentExamPaperInfo" :closeFun="closeExamPaper"></examinee-answer-sheet-view>
        </el-dialog>
    </div>
</template>
<script>
import utils from '@/utils/util'
import { getUsers } from '@/api/api'
import { getStudentsExamNumCount, getScoreCount, getScoreCountListTrend, getExamDetailInfo } from '@/api/exam'
import ExamineeAnswerSheetView from '@/components/Examination/Common/ExamineeAnswerSheetView'

export default {
    name: 'OneExaminee',
    components: {
        ExamineeAnswerSheetView
    },
    data() {
        return {
            utils: utils,
            loading: true,
            examineeOptions: [],
            searchForm: {
                accounts: '',
                accountText: '', //学生名字
                time: ''
            },
            examNumInfo: {}, // 场次统计信息
            scoreType: 1, // 1:10分区间,2:5分区间
            examInfo: {}, // 考试得分信息
            tableData: [],
            // 分页
            currentPage: 1,
            pageSize: 10,
            total: 0,
            currentExamPaperInfo: {},
            dialogExamPaper: false
        }
    },
    created() {
        this.getUserData()
    },
    methods: {
        getUserData() {
            let that = this
            getUsers({
                account: that.$store.state.userinfo.accountName, // 当前登录账号
                roleIds: '142,143,144,145,146,147,153,158,160,172,177',
            }).then(res => {
                if(res.status === 200) {
                    that.examineeOptions = res.data
                    that.$nextTick(() => {
                        // 默认选中第一个用户
                        that.searchForm.accounts = res.data[0].accountName
                        that.searchForm.accountText = res.data[0].name
                        that.search()
                    })
                }
            })
        },
        search(type) {
            // 如果是选择的考生
            if(type == 1) {
                // 记录考生中文名字
                let obj = {};
                obj = this.examineeOptions.find((item) => {
                    return item.accountName === this.searchForm.accounts;//筛选出匹配数据
                })
                this.searchForm.accountText = obj.name
            }
            this.getExamNumData()
            this.getExamScoreDistributedData()
            this.getExamScoreTrendData()
            this.getTableData()
        },
        // 获取场次统计信息
        getExamNumData() {
            let that = this
            getStudentsExamNumCount({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                accounts: that.searchForm.accounts
            }).then(res => {
                if(res.status === 200) {
                    that.examNumInfo = res.data
                    that.renderExamNumCountEchart(res.data)
                }
            })
        },
        // 渲染及格率饼图
        renderExamNumCountEchart(data) {
            // 基于准备好的dom，初始化echarts实例
            let $dom = document.getElementById('examNumCountEchart')
            if($dom) {
                this.$echarts.init($dom).setOption({
                    color: ['#47CFAD', '#FFB32D'],
                    grid: {
                        left: '3%',
                        right: '3%',
                        top: '35px',
                        bottom: '30px'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    series: [
                        {
                            name:'场次统计',
                            type:'pie',
                            radius: ['0%', '82%'],
                            avoidLabelOverlap: false,
                            label: {
                                formatter: "{b}: {c}({d}%)",
                                emphasis: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '20',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                            labelLine: {
                                normal: {
                                    show: true
                                }
                            },
                            data:[
                                {value:data.activeNum, name:'实际参考场次'},
                                {value:data.noActiveNum, name:'缺考场次'}
                            ]
                        }
                    ]
                })
            }
            this.loading = false
        },
        // 获取考试得分分布数据
        getExamScoreDistributedData() {
            let that = this
            getScoreCount({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                accounts: that.searchForm.accounts,
                type: that.scoreType,
                departmentId: -1,
                examId: -1
            }).then(res => {
                if(res.status === 200) {
                    that.examInfo = res.data
                    that.renderExamScoreDistributedEchart(res.data)
                }
            })
        },
        // 渲染得分分布柱状图
        renderExamScoreDistributedEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data.trend, (i, obj)=>{
                xData.push(obj.key)
                yData.push({
                    value: obj.value
                })
            })
            let option_echart = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return data.seriesName + '<br/>' + data.marker + data.name + '：' + data.value + '场'
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        },
                        interval:0
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    name: '数量',
                    axisTick: {
                        show: false
                    },
                    min: 0,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "得分分布",
                    type: 'bar',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('examScoreDistributedEchart')).setOption(option_echart, true);
        },
        // 获取得分走势数据
        getExamScoreTrendData() {
            let that = this
            getScoreCountListTrend({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                accounts: that.searchForm.accounts
            }).then(res => {
                if(res.status === 200) {
                    this.renderExamScoreTrendEchart(res.data)
                }
            })
        },
        // 渲染得分走势折线图
        renderExamScoreTrendEchart(data) {
            let that = this
            let xData = []
            let yData = []
            $.each(data, (i, obj)=>{
                xData.push(obj.time)
                yData.push({
                    value: obj.score,
                    name: obj.name
                })
            })
            let option_echart = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                    },
                    formatter: function (e) {
                        var data = e[0]
                        return `考生：${that.searchForm.accountText}<br/>考试：${data.name}<br/>得分：${data.value}分<br/>考试时间：${data.axisValue}`
                    }
                },
                xAxis: {
                    type: 'category',
                    axisTick: {
                        show: false
                    },
                    triggerEvent: true,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            width: 1, //这里是为了突出显示加上的
                        }
                    },
                    axisLabel: {
                        show: true,
                        rotate: -45,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 12
                        },
                        formatter: function (value, index) {
                            // 格式化成月/日，只在第一个刻度显示年份
                            if(value) {
                                let arr = value.split(' ')
                                return arr[0];
                            } else {
                                return ''
                            }
                        },
                    },
                    boundaryGap: true,
                    data: xData
                },
                yAxis: {
                    type: 'value',
                    name: '得分',
                    axisTick: {
                        show: false
                    },
                    max: 100,
                    min: 0,
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}',
                        show: true,
                        textStyle: {
                            color: '#2F3444',
                            fontSize: 14
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(55, 139, 246, 0.8)',
                            opacity: 0.7
                        }
                    },
                    axisPointer: {
                        snap: true
                    },
                    minInterval: 1
                },
                series: [{
                    name: "得分趋势",
                    type: 'line',
                    barWidth: '30',
                    itemStyle: {
                        normal: {
                            color: '#5c90d2',
                        }
                    },
                    label: {
                        formatter: '{c}',
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    },
                    data: yData
                }]
            }
            that.$echarts.init(document.getElementById('examScoreTrendEchart')).setOption(option_echart, true)
        },
        // 获取列表数据
        getTableData(pageIndex, pageSize) {
            let that = this
            that.loading = true
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            
            getExamDetailInfo({
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
                accounts: that.searchForm.accounts,
                status: -1, // 考试状态
                pageIndex: that.currentPage - 1,
                pageSize: that.pageSize,
                queryType: 1
            }).then(res => {
                if(res.status === 200) {
                    that.tableData = res.data
                    that.total = res.total
                }
                that.loading = false
            })
            
        },
        handleSizeChange(pageSize) {
            this.getTableData(1, pageSize)
        },
        handleCurrentChange(currentPage) {
            this.getTableData(currentPage)
        },
        // 导出明细
        exportDetail() {
            let that = this
            let parames = {
                account: that.searchForm.accounts,
                startTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[0] + ' 00:00:00' : '', // 创建时间
                endTime: that.searchForm.time && that.searchForm.time.length > 0 ? that.searchForm.time[1] + ' 23:59:59' : '',
            }
            let downloadUrl = this.GLOBAL.baseURL + 'exam/exportStuExamCountDetail?startTime=' + parames.startTime +
                '&endTime=' + parames.endTime +
                '&account=' + parames.account
                
            window.open(downloadUrl)
        },
        // 查看答卷明细
        handleDetail(row) {
            this.currentExamPaperInfo = row
            this.dialogExamPaper = true
        },
        closeExamPaper() {
            this.dialogExamPaper = false
        }
    }
}
</script>
<style lang="scss" scoped>
.one-examinee-analysis {
    .exam-num-count-wrap {
        .exam-num-count-list {
            padding-right: 20px;
            padding-bottom: 0;
            flex-direction: column;
            .el-col {
                margin: 10px 0;
            }
        }
        .echart-wrap {
            height: 483px;
        }
    }
}
</style>